package com.triumphxx.langchain4j.controller;

import com.triumphxx.langchain4j.dto.ChatRequest;
import com.triumphxx.langchain4j.dto.ChatResponse;
import com.triumphxx.langchain4j.service.impl.DeepSeekService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author:triumphxx
 * @Date: 2025/7/24
 * @Time: 14:18
 * @微信公众号：思考集结处
 * @网站：http://blog.triumphxx.com.cn
 * @GitHub https://github.com/triumphxx
 * @Desc: 控制器
 **/
@RestController
@RequestMapping("/api/ai")
@RequiredArgsConstructor
public class AIController {
    private final DeepSeekService deepSeekService;

    @PostMapping("/chat")
    public ResponseEntity<ChatResponse> chat(@RequestBody ChatRequest request) {
        String contextId = request.getContext();
        if (contextId == null || contextId.isEmpty() || !request.isRememberContext()) {
            contextId = deepSeekService.createNewContext();
        }

        String response = deepSeekService.chat(contextId, request.getMessage());

        return ResponseEntity.ok(ChatResponse.builder()
                .answer(response)
                .model("DeepSeek")
                .timestamp(LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME))
                .tokenUsage(response.length() / 4) // 近似估算token使用
                .contextId(contextId)
                .build());
    }

    @PostMapping("/generate-code")
    public ResponseEntity<ChatResponse> generateCode(@RequestBody ChatRequest request) {
        String contextId = request.getContext();
        if (contextId == null || contextId.isEmpty()) {
            contextId = deepSeekService.createNewContext();
        }

        String code = deepSeekService.generateCode(contextId, request.getMessage());

        return ResponseEntity.ok(ChatResponse.builder()
                .answer(code)
                .model("DeepSeek")
                .timestamp(LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME))
                .tokenUsage(code.length() / 4)
                .contextId(contextId)
                .build());
    }

    @PostMapping("/reset-context")
    public ResponseEntity<String> resetContext(@RequestParam String contextId) {
        deepSeekService.clearContext(contextId);
        return ResponseEntity.ok("上下文已重置");
    }
}
